package com.jy.app.lib.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.ActivityCompat;
import android.util.Pair;
import android.view.View;

import java.util.Iterator;
import java.util.Stack;

/**
 * Created by jan on 2016/4/13.
 */
public class ActivityUtil {

    private static final String TAG = ActivityUtil.class.getSimpleName();
    /**
     * activity栈
     */
    private static Stack<Activity> activityStack;
    /**
     * 业务相关activity栈
     */
    private static Stack<Activity> businessActivityStack;
    private static ActivityUtil instance;

    private ActivityUtil() {
    }

    public static void startActivity(Activity activity, Intent intent, Pair<View, String>... sharedElements){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            ActivityOptions options =ActivityOptions.makeSceneTransitionAnimation(activity,sharedElements);
            ActivityCompat.startActivity(activity, intent, options.toBundle());
        }else{
            activity.startActivity(intent);
        }
    }

    public static void startActivityForResult(Activity activity, Intent intent,int code ,Pair<View, String>... sharedElements){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            ActivityOptions options =ActivityOptions.makeSceneTransitionAnimation(activity,sharedElements);
            ActivityCompat.startActivityForResult(activity, intent,code, options.toBundle());
        }else{
            activity.startActivityForResult(intent,code);
        }
    }

    /**
     * TODO 添加业务相关activity到栈
     *
     * @param activity
     * @author xszhang
     * @since v0.0.1
     */
    public void addBusinessActivity(Activity activity) {
        if (businessActivityStack == null) {
            businessActivityStack = new Stack<Activity>();
        }
        businessActivityStack.add(activity);
    }

    /**
     * TODO finish业务栈
     *
     * @author xszhang
     * @since v0.0.1
     */
    public void finishBusinessStack() {
        for (int i = 0, size = businessActivityStack.size(); i < size; i++) {
            if (null != businessActivityStack.get(i)) {
                businessActivityStack.get(i).finish();
            }
        }
        businessActivityStack.clear();
    }

    /**
     * TODO 清空业务栈
     *
     * @author xszhang
     * @since v0.0.1
     */
    public void clearBussinessStack() {
        if (businessActivityStack != null) {
            businessActivityStack.clear();
            businessActivityStack = null;
        }
    }

    /**
     * 单实例 , UI无需考虑多线程同步问题
     */
    public static ActivityUtil getInstance() {
        if (instance == null) {
            instance = new ActivityUtil();
        }
        return instance;
    }

    /**
     * 添加Activity到栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    public void removeActivity(Activity activity) {
        if (activityStack != null) {
            activityStack.remove(activity);
        }
    }


    /**
     * 获取当前Activity（栈顶Activity）
     */
    public Activity currentActivity() {
        if (activityStack == null || activityStack.isEmpty()) {
            return null;
        }
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * 获取当前Activity（栈顶Activity） 没有找到则返回null
     */
    public Activity findActivity(Class<?> cls) {
        Activity activity = null;
        for (Activity aty : activityStack) {
            if (aty.getClass().equals(cls)) {
                activity = aty;
                break;
            }
        }
        return activity;
    }

    /**
     * 结束当前Activity（栈顶Activity）
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity(重载)
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            Iterator<Activity> it = activityStack.iterator();
            while (it.hasNext()) {
                Activity act = it.next();
                if (act.getClass().equals(activity.getClass())) {
                    act.finish();
                    it.remove();
                }
            }
        }
    }

    /**
     * 结束指定的Activity(重载)
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 关闭除了指定activity以外的全部activity 如果cls不存在于栈中，则栈全部清空
     *
     * @param cls
     */
    public void finishOthersActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (!(activity.getClass().equals(cls))) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 应用程序退出
     */
    @SuppressLint("MissingPermission")
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.killBackgroundProcesses(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
            System.exit(0);
        }
    }

    /**
     * 跳至Home页
     * @param context
     */
    public void toHome(Context context){
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        home.addCategory(Intent.CATEGORY_HOME);
        context.startActivity(home);
    }

}

